/*
 * huirong Inc.
 * Copyright (c) 2016 All Rights Reserved.
 * Author     :liyb
 * Create Date:2016年6月21日
 */
package cn.zs.supply.common.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;

/**
 * 字符串拼音
 */
public class PingyinUtil {

    /**
     * 提取每个汉字的拼音
     */
    public static String convert(String word) {
        try {
            return PinyinHelper.convertToPinyinString(word, "", PinyinFormat.WITHOUT_TONE);
        } catch (Exception e) {
            throw new RuntimeException("汉字转拼音异常", e);
        }
    }

    public static String namePinyin(String word, String separate) {

        String[] parts = word.split("·");
        StringBuilder builder = new StringBuilder();
        for (String part : parts) {
            String pingyin = convertToPinyinString(part, ",");
            String[] tokens = pingyin.split(",");
            for (String token : tokens) {
                if (token.length() > 1) {
                    if (builder.length() > 0) {
                        builder.append(",");
                    }
                    builder.append(token);
                } else {
                    Character c = token.charAt(0);
                    if (Character.isLetter(c)) {
                        builder.append(c);
                    }
                }

            }
        }
        return builder.toString().toUpperCase();

    }

    public static void main(String[] args) throws IOException {
        URL uri = Thread.currentThread().getContextClassLoader().getResource("aaaxxxx.txt");
        List<String> lines = FileUtils.readLines(new File(uri.getFile()), Charset.forName("utf-8"));
        for (Iterator<String> iterator = lines.iterator(); iterator.hasNext(); ) {
            String line = iterator.next();
            if (line.indexOf("/api/busiMsg") > 0) {
                iterator.remove();
            }

            if (line.indexOf("/api/fengine") > 0) {
                iterator.remove();
            }
            if (line.indexOf("HEAD /api/ HTTP/1.0") > 0) {
                iterator.remove();
            }
        }
        FileUtils.writeLines(new File("d:\\aaaxxxxbak.txt"), lines);
    }


    private static String convertToPinyinString(String str, String separator) {

        try {
            return PinyinHelper.convertToPinyinString(str, separator, PinyinFormat.WITHOUT_TONE);
        } catch (Exception e) {
            throw new RuntimeException(String.format("[%s]转拼音异常", str));
        }
    }

    public static String skipEmptyPinyin(String str) {

        if (StringUtils.isEmpty(str)) {
            return str;
        }
        return str.replaceAll("\\s+", "");
    }
}
